import React, { useState,useEffect } from 'react';
import ImgCrop from 'antd-img-crop';
import {
  LoadingOutlined,
  PlusOutlined,
  PhoneOutlined,
  SettingOutlined,
  ContactsOutlined
} from '@ant-design/icons';
import { Layout,Modal, Avatar, Select,Typography, Menu ,message,Upload, Button,  ConfigProvider,Input,Drawer, Switch,InputNumber, FloatButton, Form, Dropdown} from 'antd';
import { Route, useHistory } from 'react-router-dom/cjs/react-router-dom.min';
import Opus from './PersonOpus/Opus';

const { Header,  Content} = Layout;
const { Text } = Typography;
const {Option} = Select
const items=[
    {
        label:<SettingOutlined style={{fontSize:25}} />,
        key:'1',
        children: [
            {
              label: '修改信息',
              key: 'changemessage',
            },
            {
              label:'修改密码',
              key:'changepassword'
            },
            {
              label: '退出登录',
              key: 'outlogin',
            },
            
          ]
        
    }
]
const email =(
  <Select defaultValue="@163.com">
    <Option value="@126.com">@126.com</Option>
    <Option value="@qq.com">@qq.com</Option>
    <Option value="@163.com">@163.com</Option>
    <Option value="@gmail.com">@gmail.com</Option>
  </Select>
)

// 头像上传
const getBase64 = (img, callback) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result ));
    reader.readAsDataURL(img);
  };
  //判断是否是图片
  const beforeUpload = (file) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('您只能上传图片');
    } 
    return isJpgOrPng;
  };


const Personalpage = () => {
    const history = useHistory()
    // 第一个弹窗的上传头像和用户名有关的状态以及函数
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [confirmLoading, setConfirmLoading] = useState(false);
    const [loading, setLoading] = useState(false);
    const [imageUrl, setImageUrl] = useState();
    const [username,setUsername] =useState('阿松大')
    const [tempImagerUrl,setTempImageUrl]=useState() // 临时存储上传的头像
    const [tempUsername, setTempUsername] = useState(); // 临时存储修改的用户名
    const [isEnabled, setIsEnabled] = useState(false);//禁用修改按键
    const handleSwitchChange = (checked) => {
      setIsEnabled(checked);
      form.resetFields();
    };

    // 弹框的保存按钮
    const handleOk = () => {
        setConfirmLoading(true);
        setImageUrl(tempImagerUrl) //保存上传的头像
        setUsername(tempUsername)  //保存修改的用户名
        setTimeout(() => {
        setIsModalOpen(false);
        setConfirmLoading(false);
        }, 2000);
    };
    // 弹框的取消按钮
    const handleCancel = () => {
        setIsModalOpen(false);
    };

    // 头像上传，
    const handleChange = (info) => {
        if (info.file.status === 'uploading') {
        setLoading(true);
        return;
        }
        if (info.file.status === 'done') {
        getBase64(info.file.originFileObj , (url) => {
            setLoading(false);
            setTempImageUrl(url);  //临时存储上传的头像
        });
        }
    };
    // 用户名修改和储存
    const handleUesrnameChange =(e)=>{
      setTempUsername(e.target.value) // 临时存储修改的用户名
    }
    // 上传的样式
   const uploadButton = (
        <div>
        {loading ? <LoadingOutlined /> : <PlusOutlined />}
        <div style={{ marginTop: 8 }}>上传头像</div>
        </div>
    );
    // 第二个弹窗修改密码窗口的状态以及函数
    const [isOpen,setIsOpen] = useState(false)
    const [form] = Form.useForm()
    const handlemailOK = () => {
      form
        .validateFields()
        .then((values) => {
          console.log('Success:', values);
          // 在这里添加你的代码来处理表单提交，例如发送请求到服务器
          setIsOpen(false);
          form.resetFields();
          message.success('密码修改成功');
        })
        .catch((info) => {
          console.log('Validate Failed:', info);
        });
    };
    const handleMailCancel = () => {
      setIsOpen(false);
    };

    // 作品，喜欢和收集的路由
    const [current ,setcurrent] =useState('Opus')
    const handleOpus =({key})=>{
        setcurrent(key)
        history.push('/person/Opus')
    }
    const handleColect =({key})=>{
        setcurrent(key)
        history.push('/person/Colect')
    }
    const handleLikes =({key})=>{
        setcurrent(key)
        history.push('/person/Likes')
    }
    //关注和粉丝抽屉打开和关闭
    const [concern,setconcern]=useState(false)
    const [fans,setfans] =useState(false)
    const showConcern= ()=>{
        setconcern(true)
    }
    const onCloseconcern = ()=>{
        setconcern(false)
    }
    const showFans=()=>{
        setfans(true)
    }
    const onClosefans=()=>{
        setfans(false)
    }
    //判断是否为正确手机号
    const [phone,setphone] =useState('')
    const [isPhone,setIsphone]=useState(true)
    const handlePhone=()=>{
        const PhoneNum= /^1[3-9]\d{9}$/
        setIsphone(PhoneNum.test(isPhone))
    }
    const handleChangePhone=(newPhone)=>{
        setphone(newPhone)
        setIsphone(true)
    }
    // 设置中每一项的点击事件
    const handleMessage =(e)=>{
        if(e.key=='changemessage'){
          setIsModalOpen(true);
          setTempUsername(username);
        }
        else if(e.key=='outlogin'){
          history.push('/login')
        }
        else if(e.key=='changepassword'){
          setIsOpen(true)
        }
    }
    // 验证码按钮
    const [countdown, setCountdown] = useState(0);
    const submitClick = () =>{
          setCountdown(60);
      }
    // 定义一个禁用的按钮，手机号未输入不能点击发送验证码
    const disableButton = !phone || countdown > 0;
    // 设置定时器，进行倒计时显示
    useEffect(() => {
        if (countdown > 0) {
        const timer = setTimeout(() => {
            setCountdown(countdown - 1);
        }, 1000);
        return () => clearTimeout(timer);
        }
    }, [countdown]);


    return (
        // 主题颜色
        <ConfigProvider
        theme={{
            token: {
                // Seed Token，影响范围大
                colorPrimary: '#73d13d',
                borderRadius: 20,
                // 派生变量，影响范围小
                colorBgContainer: '#FFFAFA',
            },
        }}
        >
        <Layout>
            {/* Header头部 */}
          <Layout>
            <Header 
            style={{
                padding: 0, 
                background: '#ffffff',
                margin:10,
                height:150,
                borderRadius:30,
                display:'flex' ,
            }}
      >
            {/* 头像上传 */}
            <div style={{marginLeft:20,}} >
              <Avatar style={{margin:20}} src={imageUrl} size={90} />
            </div>
            
            {/* 用户名 */}
            <div style={{marginLeft:20,height:150,width:500}}>
              <h2 style={{marginLeft:20 ,height:40}}>{username}</h2>
              

                {/* 关注、粉丝、学校认证 */}
                <div>
                    <Button  
                    style={{color:'#8c8c8c', marginLeft:5, fontSize:10}} 
                    type='text'
                    onClick={showConcern}
                    >
                        关注: {}
                    </Button>
                    <Button 
                    style={{color:'#8c8c8c', marginLeft:20, fontSize:10}} 
                    type='text'
                    onClick={showFans}
                    >
                        粉丝: {}
                    </Button>
                    <Text style={{marginLeft:40,color:'#73d13d'}}type='secondary'>
                        <ContactsOutlined />河北师范大学
                    </Text>
                </div>
            </div>
              {/* 手机号 */}
              

                  {/* 设置 */}
                <div style={{marginLeft:'30vh'}}>
                  <Menu 
                  style={{
                      height:50,
                      width:60,
                      marginLeft:50,
                      marginTop:5,
                      borderRadius:20,
                      background:'#ffffff',
                  
                  }}
                  mode='horizontal'
                  onClick={handleMessage} 
                  selectedKeys={current} 
                  items={items}>
                  </Menu> 

                  {/* 个人信息修改窗口 */}
                  <Modal
                  title="修改信息"
                  open={isModalOpen}
                  onOk={handleOk}
                  onCancel={handleCancel}
                  confirmLoading={confirmLoading}
                  okText="保存"
                  cancelText="取消"
                  > 
                  <div style={{display:'flex', flexDirection:'column',alignItems:'center',justifyContent:'center'}}>
                  {/* 头像上传 */}
                  <div >
                    <ImgCrop shape="round" rotationSlider>
                      <Upload 
                      name="avatar" 
                      listType="picture-circle"
                      className="avatar-uploader"
                      showUploadList={false}
                      action="https://run.mocky.io/v3/435e224c-44fb-4773-9faf-380c5e6a2188" 
                      beforeUpload={beforeUpload} 
                      onChange={handleChange}
                      >
                          {tempImagerUrl ? <img src={tempImagerUrl} alt="avatar" style={{ width: '100%',borderRadius:"50%" }} /> : uploadButton}
                      </Upload>
                    </ImgCrop>
                  </div>
                    {/* 用户名 */}
                    <div style={{ height:50}}>用户名：
                      <Input 
                      style={{
                          margin:'2px auto',
                          width:250,
                          color:'black'
                      }}
                      size='large'
                      placeholder='阿松大' 
                      bordered ={false}
                      value={tempUsername}
                      onChange={handleUesrnameChange}>
                      </Input>
                      <Switch checked={isEnabled} onChange={handleSwitchChange} style={{ marginTop:10, float: 'right' }} />
                    </div>
                    
                    <Form >
                      {/* 邮箱 */}
                      <Form.Item>
                        <Input placeholder='邮箱' disabled={!isEnabled} addonAfter={email} />
                      </Form.Item>
                      {/* 手机修改 */}
                      <Form.Item
                      style={{marginTop:10 }}
                      name="phone"
                      rules={[
                        {
                          required: true,
                          message: '请输入手机号!',
                        },
                        {
                          pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
                          message: '手机号格式不正确!',
                        },
                        ]}
                      >
                      <div style={{ display: 'flex', alignItems: 'center'}}>
                        <InputNumber 
                        style={{
                          width:200,
                          color:'black'
                        }} 
                        placeholder='旧手机号'
                        disabled={!isEnabled}
                        value={phone}
                        onBlur={handlePhone}
                        onChange={handleChangePhone}
                        controls={false}
                        prefix={<PhoneOutlined />}
                        />
                      </div>
                      </Form.Item>
                      {/* 验证码 */}
                      <div style={{ display: 'flex', alignItems: 'center' }}>
                        <Input 
                        style={{
                          
                          width:80,
                        }}
                        disabled={!isEnabled}
                        controls={false}                    
                        />
                        <Button 
                        style={{
                          borderRadius:10,
                          color:'white',
                          backgroundColor:'#73d13d',
                          marginLeft:10,
                         
                        }} 
                        onClick={submitClick}
                        disabled={disableButton}
                        >
                        {countdown > 0 ? `${countdown}秒后重发` : '验证码'}
                        </Button>
                      </div>
                      <Form.Item
                      style={{marginTop:10 }}
                      name="newphone"
                      rules={[
                        {
                          required: true,
                          message: '请输入手机号!',
                        },
                        {
                          pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
                          message: '手机号格式不正确!',
                        },
                        ]}
                      >
                      <div style={{ display: 'flex', alignItems: 'center'}}>
                        <InputNumber 
                        style={{
                          width:200,
                          color:'black'
                        }} 
                        placeholder='新手机号'
                        disabled={!isEnabled}
                        
                        controls={false}
                        prefix={<PhoneOutlined />}
                        />
                      </div>
                      </Form.Item>
                      </Form>
                    </div>
                    </Modal>
                </div>
              {/* 关注列表 */}
              <Drawer 
              title='关注列表'
              placement='right'
              onClose={onCloseconcern}
              open={concern}
              closable={false}
              >
              </Drawer>
              {/* 粉丝列表 */}
              <Drawer 
              title='粉丝列表'
              placement='right'
              onClose={onClosefans}
              open={fans}
              closable={false}
              >    
              </Drawer>

              
              {/* 修改密码窗口 */}
              <Modal title="修改密码" open={isOpen} onOk={handlemailOK} onCancel={handleMailCancel}>
              <Form
                form={form}
                name="change_password"
                initialValues={{ remember: true }}
                style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}
              >
                <Form.Item
                  name="oldPassword"
                  rules={[{ required: true, message: '请输入原密码!' }]}
                >
                  <Input.Password placeholder="原密码" />
                </Form.Item>
                <Form.Item
                  name="newPassword"
                  rules={[{ required: true, message: '请输入新密码!' }]}
                >
                  <Input.Password placeholder="新密码" />
                </Form.Item>
                <Form.Item
                  name="confirmPassword"
                  dependencies={['newPassword']}
                  rules={[
                    { required: true, message: '请确认新密码!' },
                    ({ getFieldValue }) => ({
                      validator(_, value) {
                        if (!value || getFieldValue('newPassword') === value) {
                          return Promise.resolve();
                        }
                        return Promise.reject(new Error('两次输入的密码不匹配!'));
                      },
                    }),
                  ]}
                >
                  <Input.Password placeholder="确认新密码" />
                </Form.Item>
                <Form.Item
                      style={{marginTop:10 }}
                      name="phone"
                      rules={[
                        {
                          required: true,
                          message: '请输入手机号!',
                        },
                        {
                          pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
                          message: '手机号格式不正确!',
                        },
                        ]}
                      >
                      <div style={{ display: 'flex', alignItems: 'center'}}>
                        <InputNumber 
                        style={{
                          width:200,
                          color:'black'
                        }} 
                        value={phone}
                        onBlur={handlePhone}
                        onChange={handleChangePhone}
                        controls={false}
                        placeholder='手机号'
                        prefix={<PhoneOutlined />}
                        />
                      </div>
                      </Form.Item>
                <Form.Item
                  name="captcha"
                  rules={[{ required: true, message: '请输入验证码!' }]}
                >
                  <Input style={{width:100}} placeholder="验证码" />
                  <Button 
                        style={{
                          borderRadius:10,
                          color:'white',
                          backgroundColor:'#73d13d',
                          marginLeft:10,
                          marginTop:10,
                        }} 
                        onClick={submitClick}
                        disabled={disableButton}
                        >
                        {countdown > 0 ? `${countdown}秒后重发` : '验证码'}
                        </Button>
                </Form.Item>
              </Form>
            </Modal>


          </Header>
          {/* 内容部分 */}
          <Content
          style={{
            margin: '20px 16px',
            padding: 10,
            minHeight:'71vh',
            background:'#ffffff',
            borderRadius:20,
            maxHeight:'71vh',
            overflow:'auto',
          }}
          >
            <div style={{display:'flex'}}>
              <Menu 
              style={{
                  margin:'auto',
                  maxWidth:900,
                  height:40,
                  borderRadius:20,
                  background: '#ffffff',
              }}
              mode='horizontal'
              selectedKeys={current} 
              >
                  <Menu.Item
                  style={{minWidth:300 ,textAlign:'center'}}
                  key='Opus'
                  label='作品'
                  onClick={handleOpus}
                  >
                      作品
                  </Menu.Item>
                  <Menu.Item
                  style={{minWidth:300, textAlign:'center'}}
                  key='Colect'
                  label='收藏'
                  onClick={handleColect}
                  >
                      收藏
                  </Menu.Item>
                  <Menu.Item
                  style={{minWidth:300, textAlign:'center'}}
                  onClick={handleLikes}
                  key='Likes'
                  label='喜欢'
                  >
                      喜欢
                  </Menu.Item>
              </Menu>
            </div>
            {/* 路由 */}
            <Route path='/person/Opus'>
                <Opus />
            </Route>
          </Content>
          </Layout>
        </Layout>
        </ConfigProvider>
    );

};

export default Personalpage